import cv2
import numpy as np
from skimage.metrics import structural_similarity as ssim
import logging

# 配置日志记录
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

class Compare_Image:
    def __init__(self):
        logging.info("Compare_Image 类初始化完成。")

    @staticmethod
    def compare_images(image_path_a, image_path_b):
        """
        比较两张图片的相似性，并返回 MSE 和 SSIM 值。

        参数:
            image_path_a (str): 第一张图片的路径。
            image_path_b (str): 第二张图片的路径。

        返回:
            mse_value (float): 均方误差 (MSE)。
            ssim_value (float): 结构相似性指数 (SSIM)。
        """
        logging.info(f"开始比较图片: {image_path_a} 和 {image_path_b}")

        try:
            # 加载图片
            image_a = cv2.imread(image_path_a)
            image_b = cv2.imread(image_path_b)

            # 检查图片是否成功加载
            if image_a is None or image_b is None:
                logging.error("无法加载图片，请检查路径是否正确。")
                raise ValueError("无法加载图片，请检查路径是否正确。")

            # 转换为灰度图像
            gray_a = cv2.cvtColor(image_a, cv2.COLOR_BGR2GRAY)
            gray_b = cv2.cvtColor(image_b, cv2.COLOR_BGR2GRAY)

            # 确保两张图片大小一致
            if gray_a.shape != gray_b.shape:
                logging.warning("图片大小不一致，将自动调整第二张图片的大小以匹配第一张图片。")
                gray_b = cv2.resize(gray_b, (gray_a.shape[1], gray_a.shape[0]))

            # 计算 MSE
            mse_value = np.sum((gray_a - gray_b) ** 2)
            mse_value /= float(gray_a.shape[0] * gray_a.shape[1])

            # 计算 SSIM
            ssim_value, _ = ssim(gray_a, gray_b, full=True)

            logging.info(f"MSE: {mse_value}, SSIM: {ssim_value}")
            return mse_value, ssim_value

        except Exception as e:
            logging.error(f"比较图片时发生异常: {e}")
            raise Exception(f"Failed to compare images: {e}")